<style scoped>
.container {
  padding: 5px;
}

.header {
  border-bottom: 1px solid #d9d9d9;
  color: rgb(0 0 0 / 85%);
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
  cursor: pointer;
}

.header-btn {
  float: right;
}
</style>

<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <div class="header px-2 py-1.5">
      <span> {{ getTitle }}</span>
      <Authority :value="'view.save'">
        <AButton class="header-btn" type="primary" size="small" @click="handleSubmit">保存</AButton>
      </Authority>
    </div>
    <BasicForm class="container" @register="registerForm" />
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, unref, onMounted } from 'vue';
import { Authority } from '/@/components/Authority';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './menu.data';
import { getViewTree, updateView } from '/@/api/system/view';
import { watch } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';

const props = defineProps<{ value: Recordable }>()
const emit = defineEmits(['success', 'register'])
const isUpdate = ref(false);
const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));
const { notification } = useMessage();

onMounted(async () => {
  await init(props.value);
});
watch(() => props.value, (record) => {
  isUpdate.value = record.id > 0
  init(record);
}, { deep: true })

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

async function init(record: Recordable) {
  resetFields();
  if (unref(isUpdate)) {
    setFieldsValue({
      ...record,
    });
  }
  const treeData = await getViewTree();
  updateSchema({
    field: 'parentId',
    componentProps: { treeData },
  });
};



async function handleSubmit() {
  try {
    const values = await validate();
    await updateView(values);
    emit('success');
    notification.success({ message: "保存成功" })
  } catch { }
}

</script>